import { Router } from '@angular/router';
import { Injectable, Optional } from '@angular/core';
import { User, Guest, Login } from '../model/user';
import { Observable, Subject } from 'rxjs';
import { HttpService } from './http.service';

@Injectable()
export class AuthService {

    private _user: User = null;
    get isLoggedIn() {
        return (!!this._user || !!this.sessionUser) && !this._user.isExpired();
    }
    get user() { return this._user || Guest; }
    get sessionUser() {
        const token = sessionStorage.getItem('token');
        const userInfo = sessionStorage.getItem('userInfo');
        const expired = sessionStorage.getItem('expire');
        if (token && token.length) {
            this._user = new User(userInfo, token, expired);
            return this._user;
        }
        return null;
    }

    // 用于记录未登录之前尝试的页面
    backUrl = '';

    constructor(
        private http: HttpService,
        private router: Router
    ) { }

    // MOCK LOGIN
    loginRequestMock(userName, pwd) {
        return Observable
            .of(new User({ name: userName, admin: userName === 'Admin' }))
            .delay(500)
            .do(x => {
                this._user = x;
                sessionStorage.setItem('token', x.token);
                sessionStorage.setItem('userInfo', JSON.stringify(x.userInfo));
                sessionStorage.setItem('expire', x.expire);
            });
    }

    loginRequest(userName, pwd) {
        return this.http.post('api/login', {
            loginName: userName,
            password: pwd
        }).map(data => {
            if (data['head']['status'] === 1) {
                return new User(
                    data['body']['userInfo'],
                    data['body']['token']);
            }
            throw false;
        }).do(x => {
            this._user = x;
            sessionStorage.setItem('token', x.token);
            sessionStorage.setItem('userInfo', x.userInfo);
            sessionStorage.setItem('expire', x.expire);
        });
    }

    login(userName, pwd) {
        return this.loginRequestMock(userName, pwd);
    }

    logout(safe = false) {
        this._user = null;
        sessionStorage.removeItem('token');
        sessionStorage.removeItem('userInfo');
        sessionStorage.removeItem('expire');
        if (safe) {
            return Observable.of(true);
            // return this.http.post('api/loginout', {})
        } else {
            return Observable.of(true);
        }
    }

    redirectAfterLogin() {
        if (this.backUrl && this.backUrl.length) {
            const url = this.backUrl;
            this.backUrl = '';
            this.router.navigate([url]);
        } else {
            this.router.navigate(['home']);
        }
    }

}